/**
 * http://www.koorz.com
 * Copyright (c) 2012 shanghai meiku information technology co,.ltd
 */
package com.koorz.jfinal.lucene;

import java.util.ArrayList;
import java.util.List;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.PhraseQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.spans.SpanNearQuery;
import org.apache.lucene.search.spans.SpanQuery;
import org.apache.lucene.search.spans.SpanTermQuery;
import org.apache.lucene.util.Version;

/**
 * 功能描述：
 * 作        者：尹东东 
 * 创建时间：2013-4-4 上午11:14:31
 * 版  本  号：1.0
 */
public class BlankAndQueryParser extends QueryParser {

	public BlankAndQueryParser(Version matchVersion, String f, Analyzer a) {
		super(matchVersion, f, a);
	}

	@Override
	protected Query getFieldQuery(String field,
			String queryText, int slop) throws ParseException {
		List<String> tokens = SearchHelper.splitKeywords(queryText);
		if(tokens.size() == 0)return null;
		else if(tokens.size() == 1)return new TermQuery(new Term(field, new String(tokens.get(0))));
		else {
			PhraseQuery q = new PhraseQuery();
			q.setBoost(2048.0f);
			q.setSlop(1);
			List<SpanQuery> s = new ArrayList<SpanQuery>(tokens.size());
			for(int i=0;i<tokens.size();i++){
				q.add(new Term(field,tokens.get(i)));
				SpanTermQuery tmp = new SpanTermQuery(new Term(field,tokens.get(i)));
				s.add(tmp);
			}
			BooleanQuery bQuery = new BooleanQuery();
			bQuery.add(q,BooleanClause.Occur.SHOULD);
			SpanNearQuery nearQuery = new SpanNearQuery(s.toArray(new SpanQuery[s.size()]),s.size(),false);
			nearQuery.setBoost(0.001f);
			bQuery.add(nearQuery,BooleanClause.Occur.SHOULD);
			return bQuery;
		}
	}
	
	@Override
	protected Query getFieldQuery(String field,
			String queryText, boolean quoted) throws ParseException {
		return getFieldQuery(field, queryText, 0);
	}
}
